package com.eventos.error;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;

import android.content.Context;

import com.ofek.eventos.R;

public class ErrorReport {
	private static final String SUPPORT_EMAIL = "ofekron89@gmail.com";
	private static Context ctx;
	public static class CustomExceptionHandler implements UncaughtExceptionHandler {

		private final UncaughtExceptionHandler defaultUEH;

		/* 
		 * if any of the parameters is null, the respective functionality 
		 * will not be used 
		 */
		public CustomExceptionHandler() {
			defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
		}

		@Override
		public void uncaughtException(final Thread t, final Throwable e) {


			new Thread() {
				@Override
				public void run() {
					try {
						final Writer result = new StringWriter();
						final PrintWriter printWriter = new PrintWriter(result);
						e.printStackTrace(printWriter);
						final String stacktrace = result.toString();
						printWriter.close();
						MailUtils.sendMail(SUPPORT_EMAIL, "Crash Report from "+ctx.getString(R.string.app_name)+ " ver. "+ctx.getString(R.string.app_version) , stacktrace);
					} catch (final Exception e1) {
						e1.printStackTrace();
					}
				}
			}.start();


			defaultUEH.uncaughtException(t, e);


		}
	}
	public static void init(final Context c) {
		ctx = c;
		Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler());
	}
	
}
